import axios from "axios";
import Request from "@/api/request";
import { message } from "ant-design-vue";
import router from "./router/index.js"
function hasToken() {
    const token = localStorage.getItem("Authorization");
    return (token !== null);
}
function setToken(token) {//存入AccessToken //在登录表单等地方需要调用该函数存入token
    localStorage.setItem("Authorization", token);
}
function getProfile()//获取用户信息存储在localstorage中
{
    console.log("获取用户信息:")
    Request({
        method: 'GET',
        url: "/user/userInfoWithRole",
    }).then(response => {
      const responseData=response.data
      console.log("返回的data:",responseData.data)
      const nickname = responseData.data.nickname;
      const email =responseData.data.email;
      const userPic =responseData.data.userPic;
      const userId =responseData.data.userId;
      const roleName = responseData.data.roleName;
      const roleId = responseData.data.roleId;
      if((responseData.data === null)==false){
        message.success("你好!"+nickname)
        localStorage.setItem("roleId",roleId)
        localStorage.setItem("roleName",roleName)
        localStorage.setItem("nickname",nickname)
        localStorage.setItem("email",email)
        localStorage.setItem("userPic",userPic)
        localStorage.setItem("userId",userId)
      }else{
        message.error("获取用户信息失败")
      }
      return responseData
    }, error => {
    console.log('错误', error.message)
    })
}

function logout() {
    //清除localStorage的存储
    localStorage.removeItem("Authorization");
    localStorage.removeItem("username");
    localStorage.removeItem("email");
    localStorage.removeItem("userPic");
    localStorage.removeItem("nickname");
    localStorage.removeItem("userId");
    localStorage.removeItem("roleId")
    localStorage.removeItem("roleName")
    router.replace({ path: "/login" });
    console.log("退出登录")
    message.success('已退出登录')
}

export default {
    hasToken,
    setToken,
    getProfile,
    logout
};